package com.bys.admin.ai.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bys.admin.ai.controller.vo.ChatPageReqVO;
import com.bys.admin.ai.controller.vo.ChatSaveReqVO;
import com.bys.admin.ai.entity.Chat;
import com.bys.admin.ai.mapper.ChatMapper;
import com.bys.admin.ai.service.ChatService;
import com.bys.exception.ServiceException;
import com.github.yulichang.base.MPJBaseServiceImpl;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;
import com.bys.util.BeanUtils;

import java.time.LocalDateTime;
import java.util.List;

import static com.bys.constant.ErrorCodeConstant.CHAT_NOT_EXISTS;
import static com.bys.util.CollectionUtils.convertList;


/**
 * AI Chat 对话 Service 实现类
 *
 * @author 系统管理员
 */
@Service
@Validated
public class ChatServiceImpl  extends MPJBaseServiceImpl<ChatMapper, Chat> implements ChatService {

    @Resource
    private ChatMapper chatMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createChat(ChatSaveReqVO createReqVO) {
        // 插入
        Chat chat = BeanUtils.toBean(createReqVO, Chat.class);
        chatMapper.insert(chat);
        // 返回
        return chat.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateChat(ChatSaveReqVO updateReqVO) {
        // 校验存在
        validateChatExists(updateReqVO.getId());
        // 更新
        Chat updateObj = BeanUtils.toBean(updateReqVO, Chat.class);
        if (Boolean.TRUE.equals(updateReqVO.getPinned())) {
            updateObj.setPinnedTime(LocalDateTime.now());
        }
        chatMapper.updateById(updateObj);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteChat(Long id) {
        // 校验存在
        validateChatExists(id);
        // 删除
        chatMapper.deleteById(id);
    }

    private void validateChatExists(Long id) {
        if (chatMapper.selectById(id) == null) {
            throw new ServiceException(CHAT_NOT_EXISTS);
        }
    }
    @Override
    public Chat getChat(Long id) {
        return chatMapper.selectById(id);
    }
    @Override
    public Page<Chat> getChatPage(ChatPageReqVO pageReqVO) {
    return chatMapper.selectPage(pageReqVO);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long createChatMy(ChatSaveReqVO createReqVO, Long userId) {
//        获取模型
        Chat chat = Chat.builder().userId(userId).pinned(Boolean.FALSE).modelId(null).temperature(null).maxTokens(null).maxContexts(null).build();
        chat.setTitle(Chat.TITLE_DEFAULT);
       chatMapper.insert(chat);
        return chat.getId();
    }

    @Override
    public List<Chat> listByUserId(Long userId) {
        return list(new LambdaQueryWrapper<Chat>().eq(Chat::getUserId,userId).orderByDesc(Chat::getCreateTime));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteChatMyByUnpinned(Long userId) {
        List<Chat> list = chatMapper.selectList(new LambdaQueryWrapper<Chat>().eq(Chat::getUserId,userId).eq(Chat::getPinned,false));
        if (CollUtil.isEmpty(list)) {
            return;
        }
        chatMapper.deleteBatchIds(convertList(list, Chat::getId));
    }
}